const express = require('express');
const { User } = require('../../models');
const { success, failure } = require('../../utils/responses');
const router = express.Router();
const { Op } = require('sequelize');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { BadRequest } = require('http-errors');

router.post('/login', async (req, res) => {
  try {
    const { username, email, password } = req.body;
    if (!username && !email) {
      throw BadRequest('请输入用户名或邮箱');
    }
    if (!password) {
      throw BadRequest('请输入密码');
    }

    const user = await User.findOne({
      where: { [Op.or]: [{ email: email || '' }, { username: username || '' }] },
    });
    if (!user) {
      throw BadRequest('用户不存在');
    }
    if (user.role != 100) {
      throw BadRequest('权限不足,后台只能管理员登录');
    }
    const isPasswordValid = bcrypt.compareSync(password, user.password);

    if (!isPasswordValid) {
      throw BadRequest('密码错误。');
    }

    // 生成身份验证令牌
    const token = jwt.sign(
      {
        userId: user.id,
      },
      process.env.SECRET,
      { expiresIn: process.env.EXPIRES_TIME }
    );
    success({ res, data: token, message: '登录成功' });
  } catch (error) {
    failure({ res, error });
  }
});
module.exports = router;
